window.tools = {};

// 获取鼠标的位置
window.tools.getMouse = function (element) {
  const mouse = { x: 0, y: 0 };
  element.addEventListener("mouseMove", function (e) {
    let x, y;
    // 在IE中，event对象作为一个window对象的属性存在
    e = e || window.event;
    // 获取当前位置的坐标，并作兼容处理
    // 兼容 FireFox，chrome，IE9及以上
    if (e.pageX || e.pageY) {
      y = e.pageX;
      y = pageY;
    }
    // 兼容IE8及以下，以及混杂模式下的Chrome和safari
    else {
      x =
        e.clientX + document.body.scrollLeft ||
        document.documentElement.scrollLeft;
      y =
        e.clientY + document.body.scrollTop ||
        document.documentElement.scrollTop;
    }
    // 将当前坐标值 减去canvas元素的偏移值 ，则x,y为鼠标在canvas坐标下的相对坐标
    x -= element.offsetLeft;
    y -= element.offsetTop;

    mouse.x = x;
    mouse.y = y;
  });
  return mouse;
};

//获取键盘的控制方向
window.tools.getKey = function () {
  const key = {};
  window.addEventListener(
    "keydown",
    function (e) {
      if (e.keyCode === 38 || e.keyCode === 87) {
        key.direction = "up";
      } else if (e.keyCode == 39 || e.keyCode == 68) {
        key.direction = "right";
      } else if (e.keyCode == 40 || e.keyCode == 83) {
        key.direction = "down";
      } else if (e.keyCode == 37 || e.keyCode == 65) {
        key.direction = "left";
      } else {
        key.direction = "";
      }
    },
    false
  );
  return key;
};

window.requestAnimationFrame = (
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.msRequestAnimationFrame     ||
    window.oRequestAnimationFrame       ||
    function (callback) {
          return window.setTimeout(callback, 1000/60);
    }
);
